#include <iostream>
#include <unistd.h>

#include "edaParSearchWrapper.ph"

edaParSearchWrapper::edaParSearchWrapper()
  : searchAlgorithm (NULL), 
    status (STATUS_PENDING), 
    sol (NULL)
{
}

edaParSearchWrapper::edaParSearchWrapper(edaBuffer &_buf) 
  : status (STATUS_PENDING), 
    sol(NULL)
{
  // New search object
  searchAlgorithm = (edaSearch*)classGenerateFromBuffer( _buf );
}

edaParSearchWrapper::~edaParSearchWrapper()
{
  if (searchAlgorithm != NULL)
  {
    delete searchAlgorithm;
  }

  if (sol != NULL)
  {
    delete sol;
  }
}

void edaParSearchWrapper::setSolution( edaBuffer &_buf )
{
  /* Clean up old solution */
  if (sol != NULL)
  {
    delete sol;
  }

  sol = (edaSolution*) classGenerateFromBuffer(_buf);
}

void edaParSearchWrapper::getSolution( edaBuffer &_buf_out)
{
  sol->doSerialize(_buf_out, true);
}

void edaParSearchWrapper::getCurrentStatus(int &_status)
{
  printDebug(5, "status = " << status);
  _status = status;
}

void edaParSearchWrapper::search( edaBuffer &_buf_in )
{
  char hostname[255];
  gethostname(hostname, 254);
  rprintf("Running search on %s\n", hostname);

  // Create new solution object
  setSolution(_buf_in);

  // Set search status
  status = STATUS_RUNNING;

  printDebug(4, "Before search, status: " << status);
  // Call search algorithm
  searchAlgorithm->search(*sol);

  // Set search status
  status = STATUS_FINISHED;

  printDebug(4, "After search, status: " << status);
}

void edaParSearchWrapper::search( edaBuffer &_buf_in, edaBuffer &_buf_out)
{
  search(_buf_in);
}

void edaParSearchWrapper::setAlgorithm(edaBuffer &_buf)
{
  if (searchAlgorithm != NULL)
  {
    delete searchAlgorithm;
  }

  searchAlgorithm = (edaSearch*)classGenerateFromBuffer( _buf );
}
